import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;


import javax.servlet.*;
import javax.servlet.http.*;

//import by.epam.communalservices.entity.User;
import by.epam.communalservices.special.ResourceManager;
import by.epam.communalservices.utils.Lang;

@SuppressWarnings("serial")
public class MainServer extends HttpServlet {
    /**
     * 
     */

    ServletContext context;


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // System.out.println(" ****** call ******** ");
            context = getServletConfig().getServletContext();
            

            String cpt = request.getContextPath();
            String uri = request.getRequestURI();
            String trg = uri.substring(cpt.length(), uri.length());
            String rea = uri.substring(cpt.length(), uri.lastIndexOf("/"));

            ResourceManager rm = new ResourceManager(context.getRealPath(""));
            rm.addResourceLogic("js", "text/javascript; charset=windows-1251");
            rm.addResourceLogic("css", "text/css");
            rm.addResourceLogic("png", "image/png");
            rm.addResourceLogic("gif", "image/gif");
            rm.addResourceLogic("jpg", "image/jpeg");
            if (rm.isResourceURI(trg)) {
                try {
                    File file = new File(rm.getSelectorPath());
                    response.setContentLength((int) file.length());
                    if (rm.getSelected().getMime()!="") {
                        response.setHeader("Content-type", rm.getSelected().getMime());
                    }

                    FileInputStream in = new FileInputStream(file);
                    OutputStream out = response.getOutputStream();

                    byte[] buf = new byte[1024];
                    int count = 0;
                    while ((count = in.read(buf)) >= 0) {
                        out.write(buf, 0, count);
                    }
                    in.close();
                    out.close();

                    return;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            
            Lang.setLang("rus");
            Cookie[] cookies = request.getCookies();
            if (cookies != null)
            for (int i =0; i< cookies.length; i++) {
                Cookie c = cookies[i];
                if (c.getName().equals("lang")) {
                    Lang.setLang(context.getRealPath("WEB-INF/"+c.getValue()+".properties"));
                    request.setAttribute("currentLang", c.getValue());
                }
            }
            
            request.setAttribute("reacted", rea);
            request.setAttribute("servletName", "MainServletJspLoader");
            Boolean logined = false;
            if (request.getSession().getAttribute("currentUser") != null) {
                logined = true;
            }
            request.setAttribute("logined",logined);

            
            if (!logined) {
                request.setAttribute("target", trg);
                context.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
            } else if (trg.equals("/")) {
                request.setAttribute("target", "/WEB-INF/pages/index.jsp");
                context.getRequestDispatcher("/WEB-INF/jsp/common.jsp").forward(request, response);
            } else {
                String jsp = "/WEB-INF/pages" + trg + ".jsp";
                File f = new File(context.getRealPath(jsp));
                
                if (!f.isFile()) {
                    request.setAttribute("target", trg);
                    context.getRequestDispatcher("/WEB-INF/jsp/404.jsp").forward(request, response);
                    // res.sendError(404);
                } else {
                    request.setAttribute("target", jsp);
                    context.getRequestDispatcher("/WEB-INF/jsp/common.jsp").forward(request, response);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            request.setAttribute("message", ex.getMessage());
            request.setAttribute("stackTrace", ex.getStackTrace());
            context.getRequestDispatcher("/WEB-INF/jsp/500.jsp").forward(request, response);
        }

    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // System.out.println(" ****** call ******** ");
            context = getServletConfig().getServletContext();

            String cpt = request.getContextPath();
            String uri = request.getRequestURI();
            String trg = uri.substring(cpt.length(), uri.length());
            String rea = uri.substring(cpt.length(), uri.lastIndexOf("/"));

            Lang.setLang("rus");
            Cookie[] cookies = request.getCookies();
            if (cookies != null)
            for (int i =0; i< cookies.length; i++) {
                Cookie c = cookies[i];
                if (c.getName().equals("lang")) {
                    Lang.setLang(context.getRealPath("WEB-INF/"+c.getValue()+".properties"));
                    request.setAttribute("currentLang", c.getValue());
                }
            }
            
            request.setAttribute("reacted", rea);
            request.setAttribute("servletName", "MainServletJspLoader");
            Boolean logined = false;
            if (request.getSession().getAttribute("currentUser") != null) {
                logined = true;
            }
            request.setAttribute("logined",logined);

            
            if (!logined || trg.equals("/login") ) {
                request.setAttribute("target", trg);
                context.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
            } else {
                String jsp = "/WEB-INF/pages" + trg + ".jsp";
                File f = new File(context.getRealPath(jsp));
                if (!f.isFile()) {
                    request.setAttribute("target", trg+" + "+context.getRealPath(jsp));
                    context.getRequestDispatcher("/WEB-INF/jsp/404.jsp").forward(request, response);
                    // res.sendError(404);
                } else {
                    request.setAttribute("target", jsp);
                    context.getRequestDispatcher("/WEB-INF/jsp/common.jsp").forward(request, response);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            
            request.setAttribute("message", ex.getMessage()+"<br>"+ex.toString());
            request.setAttribute("stackTrace", ex.getStackTrace());
            request.setAttribute("stackCause", ex.getCause().getStackTrace());
            context.getRequestDispatcher("/WEB-INF/jsp/500.jsp").forward(request, response);
        }

    }

}
